package cn.itcast.bos.service.take_delivery.impl;

import java.util.Date;
import java.util.Iterator;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.constant.Constants;
import cn.itcast.bos.dao.base.AreaRepository;
import cn.itcast.bos.dao.base.FixedAreaRepository;
import cn.itcast.bos.dao.take_delivery.OrderRepository;
import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.domain.base.SubArea;
import cn.itcast.bos.domain.take_delivery.Order;
import cn.itcast.bos.domain.take_delivery.WorkBill;
import cn.itcast.bos.service.take_delivery.OrderService;
import cn.itcast.bos.service.take_delivery.WorkBillService;
import cn.itcast.crm.domain.Customer;
@Service
@Transactional
public class OrderServiceImpl implements OrderService {
	
	@Autowired
	private OrderRepository orderRepository;
	@Autowired
	private AreaRepository areaRepository;
	@Autowired
	private FixedAreaRepository fixedAreaRepository; 
	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;
	@Autowired
	private WorkBillService workBillService;
	
	@Override
	public void save(Order order) {
		//对order进行关联操作后保存
		//订单号
		String orderNum = RandomStringUtils.randomNumeric(6);
		order.setOrderNum(orderNum);
		order.setTelephone(order.getSendMobile());
		//订单代取状态
		order.setStatus("1");
		//下单时间
		order.setOrderTime(new Date());
		/**
		 * org.hibernate.TransientPropertyValueException
		 */
		Area sendArea = order.getSendArea();
		Area recArea = order.getRecArea();
		Area persistsendArea = areaRepository.findByProvinceAndCityAndDistrict(sendArea.getProvince(),
				sendArea.getCity(),sendArea.getDistrict());
		Area persistrecArea = areaRepository.findByProvinceAndCityAndDistrict(recArea.getProvince(),
				recArea.getCity(),recArea.getDistrict());
		order.setSendArea(persistsendArea);
		order.setRecArea(persistrecArea);
		/**
		 * 查询数据库，根据实际情况（寄件地址）是否已存在关联的快递员
		 */
		System.out.println("寄件地址："+order.getSendAddress());
		Customer c = WebClient.create(Constants.CRM_MANAGEMENT+"/services/customerService/findFixedIdByAddress/"+order.getSendAddress())
				.accept(MediaType.APPLICATION_JSON).get(Customer.class);
		if(c != null){
			String fixedAreaId = c.getFixedAreaId();
			if(fixedAreaId != null){
				//存在关联的定区
				FixedArea fixedArea = fixedAreaRepository.findOne(fixedAreaId);
				//这里只取一个关联的送派员，不分远近
				//failed to lazily initialize a collection of role: cn.itcast.bos.domain.base.FixedArea.couriers, could not initialize proxy - no Session
				Courier courier = fixedArea.getCouriers().iterator().next();
				if(courier != null){
						//说明定区存在这样的送派员,关联到order
						order.setCourier(courier);
						//设置分单类型为1自动分单
						order.setOrderType("1");
						//发送短信
						sendMessage(order);
						//生成工单
						WorkBill workBill = createWorkBill(order);
						order.getWorkBills().add(workBill);
						System.out.println("完全匹配的寄件人地址查询方式保存~~~~~");
						orderRepository.save(order);
						return ;
					}
			}
		}
		/**
		 * 根据分区的关键字匹配查找或者分区的辅助关键字符合的送派员keyWords
		 */
		
		//遍历area，查找符合条件的分区
		for(SubArea subArea : persistsendArea.getSubareas()){
			if(order.getSendAddress().contains(subArea.getKeyWords()) || order.getSendAddress().contains(subArea.getAssistKeyWords())){
				//有符合关键字的分区,查找其中一个，不分远近
				Iterator<Courier> iterator = subArea.getFixedArea().getCouriers().iterator();
				if(iterator.hasNext()){
					//关联order
					order.setCourier(iterator.next());
					order.setOrderType("1");
					//发送短信
					sendMessage(order);
					//生成工单
					WorkBill workBill = createWorkBill(order);
					order.getWorkBills().add(workBill);
					System.out.println("关键字或辅助关键字地址匹配的方式查询保存~~~~~");
					orderRepository.save(order);
					return;
				}
			}
		}
		/**
		 * 人工分单
		 */
		System.out.println("人工分单，自动保存订单");
		orderRepository.save(order);
		createWorkBill(order);
		
			
	}
	
	/**
	 * 分送短信功能
	 */
	private void sendMessage(Order order){
		jmsTemplate.send("callCustomer", new MessageCreator() {
			@Override
			public Message createMessage(Session session) throws JMSException {
				Message message = session.createMessage();
				message.setStringProperty("work", "xxx请求收取快递");
				return message;
			}
		});
		System.out.println("此次订单寄件人"+order.getSendName()+"电话："+order.getSendMobile());
	}
	/**
	 * 生成工单功能
	 */
	private WorkBill createWorkBill(Order order){
		WorkBill w = new WorkBill();
		w.setType("新");
		w.setBuildtime(new Date());
		w.setOrder(order);
		w.setRemark(order.getRemark());
		w.setPickstate("0");
		w.setCourier(order.getCourier());
		workBillService.save(w);
		return w;
	}

	@Override
	public Order findByOrderNum(String orderNum) {
		return orderRepository.findByOrderNum(orderNum);
	}

}
